<template>
  <div class="cart-bottom-bar">
    <check-button class="select-all" :is-checked="isSelectAll" @click.native="checkClick"></check-button>
    <span>全选</span>
    <span class="total-price">合计: ¥{{totalPrice}}</span>
    <span class="buy-product" @click="checkOut">去计算({{$store.getters.cartCount}})</span>
  </div>
</template>

<script>
  import CheckButton from "components/content/checkButton/CheckButton"

  import { mapGetters } from "vuex"

  export default {
    name: "BottomBar",
    components: {
      CheckButton
    },
    computed: {
      ...mapGetters(['cartList']),
      totalPrice() {
        // let totalP = 0
        // for (let item of this.$store.getters.cartList) {
        //   if (item.checked) {
        //     totalP += item.price * item.count
        //   }
        // }
        // return totalP
        // ----------
        // 以下代码等同上面注释代码
        return this.cartList.filter(item => {
          return item.checked
        }).reduce((preValue, item) => {
          return preValue + item.count * item.price
        }, 0).toFixed(2)
      },
      isSelectAll() {
        // 当没有商品时，不选中
        if ( this.cartList.length === 0 ) return false
        // 当有一个商品不选中，全选按钮都不选中
        // return !(this.cartList.filter(item => !item.checked).length)
        return !(this.cartList.find(item => !item.checked))
      }
    },
    methods: {
      checkClick() {
        // 全选按钮点击事件
        if (this.isSelectAll) {
          this.cartList.forEach(item => item.checked = false)
        } else {
          this.cartList.forEach(item => item.checked = true)
        }
      },
      checkOut() {
        // 去计算按钮，判断是否选择了商品，需至少选中一个商品
        const checkedItem = this.cartList.find(item => item.checked)
        if ( !checkedItem ) {
          this.$toast.show('请先选择商品')
        }
      }
    }
  }
</script>

<style scoped>
  .cart-bottom-bar {
    width: 100%;
    height: 44px;
    background-color: #eee;
    position: fixed;
    bottom: 49px;
    left: 0;
    box-shadow: 0 -2px 3px rgba(0, 0, 0, .2);
    font-size: 14px;
    color: #888;
    line-height: 44px;
    padding-left: 35px;
    box-sizing: border-box;
  }

  .cart-bottom-bar .select-all {
    position: absolute;
    line-height: 0;
    left: 12px;
    top: 13px;
  }

  .cart-bottom-bar .total-price {
    margin-left: 15px;
    font-size: 16px;
    color: #666;
  }

  .cart-bottom-bar .buy-product {
    background-color: orangered;
    color: #fff;
    width: 100px;
    height: 44px;
    text-align: center;
    line-height: 44px;
    float: right;
  }
</style>
